var mymap;
var baseLayers;
var location;
var imgPath;
var markertype=0;
var locateMarkers=[];
var time=0;
var cesium=false;
var rule;
var indoorMap=false;
var http="http://19.16.71.127:7788/geoserver/cite/wms?";
window.onload=initMap();

function initMap(){
http=window.Android.getURL()+"/geoserver/cite/wms?";
createMap();
}

function createMap() {
    mymap=L.map('map',{
        attributionControl:false,
        zoomControl:false,
        center: [34.83, 113.57],
        zoom: 14
    });
    mymap.addEventListener('zoom',function(){

    if(mymap.getZoom()>=17&&indoorMap==false){
    indoorMap=true;
    layerManager.switchLayer(0);
    window.Android.startFloor();
    }else if(mymap.getZoom()<17&&indoorMap){
    indoorMap=false;
    window.Android.endFloor();
    layerManager.removeCurrentLayer();
    }
    });
    initLayer();

    initWmsLayer();
}

/**
 * 初始化图层
 */
function initLayer() {

    /**
     * 来自天地图的地形
     */

    var terrain = L.tileLayer.chinaProvider('TianDiTu.Terrain.Map', {
        maxZoom: 18,
        minZoom: 5
    });
    var terrainAn = L.tileLayer.chinaProvider('TianDiTu.Terrain.Annotion', {
        maxZoom: 18,
        minZoom: 5
    });
    var terrainLayer = L.layerGroup([terrain, terrainAn]);

    /**
     * 来本地的影像
     */
    var TitleLayer=L.tileLayer.wms(http,{
        layers:'cite:image',
        crs:L.CRS.EPSG4326,
        format: 'image/png',
        transparent:true,
        maxZoom: 33,
        minZoom: 14
    });

    /**
     * 来自智图的多种颜色地图
     */
    var baseMap = L.tileLayer.chinaProvider('Geoq.Normal.Map',{
        maxZoom: 18,
        minZoom: 5
    });
    var colorMap = L.tileLayer.chinaProvider('Geoq.Normal.Color', {
        maxZoom: 18,
        minZoom: 5
    });
    var blueLayer = L.tileLayer.chinaProvider('Geoq.Normal.PurplishBlue', {
        maxZoom: 18,
        minZoom: 5
    });
    var grayLayer = L.tileLayer.chinaProvider('Geoq.Normal.Gray', {
        maxZoom: 18,
        minZoom: 5
    });

    baseLayers = [colorMap, blueLayer, grayLayer, TitleLayer, terrainLayer];
    mymap.addLayer(baseMap);

}
/**
 * 初始化wms图层
 */
function initWmsLayer() {
    layerManager.setMap(mymap);
    var layerNameGroup=["F1","F2","F3","F4","F5"];
    for(var i=0;i<layerNameGroup.length;i++){
        console.log(layerNameGroup[i]);
        var s=layerNameGroup[i];
        var workSpace='indoor';
        var httpNew=http.replace('cite',workSpace);
        layerManager.addLayer(httpNew,
            workSpace+':'+layerNameGroup[i]
            ,s)
    }
}

/**
 * 切换图层
 * @param id 图层的序号
 */
function tabLayer(id) {
    //如果三维存在，点击其他则移除三维
    if(cesium&&id!=5){
        removeDiv("iframe");
        var box=document.getElementsByClassName("mapLi");
        for(var i=0;i<box.length;i++){
            box[i].style.display="block";
        }
        cesium = false;
    }
    for(var i=0;i<baseLayers.length;i++){
        //添加三维
        if (id == 5) {
            addCesium();
            cesium = true;
            return;
        }
        //移除现有地图
        if(mymap.hasLayer(baseLayers[i])){
            mymap.removeLayer(baseLayers[i]);
            break;
        }
    }
    //移除室内地图
    if(indoorMap){
        layerManager.removeCurrentLayer();
    }
    //添加底图
    baseLayers[id].addTo(mymap);
    //添加室内底图
    if(indoorMap){
        layerManager.recoverCurrentLayer();
    }
}
/**
 * android调用切换楼层
 * @param i{number}
 */
function switchLayer(i) {
    layerManager.switchLayer(i);
}
function addCesium() {
    var iframe=document.createElement('iframe');
    iframe.id="iframe";
    iframe.src="test.html";
    document.body.appendChild(iframe);
    var box=document.getElementsByClassName("mapLi");
    for(var i=0;i<box.length;i++){
       box[i].style.display="none";
    }
}

/**
 * 放大地图
 */
function mapLarger() {
    if(mymap.getZoom()==mymap.getMaxZoom()){
        document.getElementById("zoomIn").style.backgroundImage='url(img/zoominmin.png)';
    }else {
        document.getElementById("zoomOut").style.backgroundImage='url(img/zoomout.png)';
        mymap.zoomIn(1,true);}
}

/**
 * 缩小地图
 */
function mapSmaller() {
    if(mymap.getZoom()==mymap.getMinZoom()){
        document.getElementById("zoomOut").style.backgroundImage='url(img/zoomoutmax.png)';
    }else {
            document.getElementById("zoomIn").style.backgroundImage='url(img/zoomin.png)';
        mymap.zoomOut(1,true);
    }
}


/**
 * 接收一次来自Android的位置
 */
function getLocation(){
 window.Android.getLocation();
}
function moveToCenter(obj){
if(obj == null){showMessage("尚未开启定位");}else{
  var arr = JSON.stringify(obj);
    var json = JSON.parse(arr);
       mymap.panTo([json.Latitude, json.Longitude]);
       }
}
/**
 * 开启Android定位
 */
function receivePosition(obj) {
    var arr = JSON.stringify(obj);
    var json = JSON.parse(arr);

    /**
     * 把Json传递给location会引起崩溃
     */
    if(locateMarkers.length!=0){
        for(var i=0;i<locateMarkers.length;i++){
            mymap.removeLayer(locateMarkers[i]);
        }
    }
    var marker = L.marker([json.Latitude, json.Longitude]).addTo(mymap);
    locateMarkers.push(marker);
    var con =
        "纬度：" + json.Latitude +
        "<br/>经度：" + json.Longitude +
        "<br/>高度：" + json.Altitude +
        "<br/>平面精度：" + json.Accuracy +
        "<br/>速度：" + json.Speed +
        "<br/>朝向：" + json.Bearing;
    marker.bindPopup(con);
    marker.on('click', function () {
        if(time != 0){
            time=new Date().getTime()-time;
            if (time < 1200) {
                mymap.removeLayer(marker);
                time = 0;
            }else{
                time=new Date().getTime();
            }
        }else{
            time=new Date().getTime();
        }
    });
}

/**
 * 测量
 */
function chooseMeasure() {
    var div=document.createElement('div');
    div.id="message";
    document.body.appendChild(div);
    div.innerHTML=
        "<div class='measure' onclick='measureDis()'>测距离</div>" +
        "<div class='measure' onclick='measureArea()'>测面积</div>" +
        "<div id='removeMessage' onclick='removeParent(this)'>取消</div>";
}
function createCloseBtn() {
    var div=document.createElement("div");
    div.id="closeMeasure";
    div.textContent="结束测量";
    document.body.appendChild(div);
    return div;
}
//测距
function measureDis() {
    removeDiv("message");
    var p2=null;
    var p=null;
    var mlatlng=null;
    var num=0;
    var line=null;
    var popup=null;
    var aDis=0;
    var points=[];
    var cacheLayer=new L.FeatureGroup();
    var closeMbtn=createCloseBtn();
    closeMbtn.addEventListener("click",function () {
        mymap.removeLayer(cacheLayer);
        if(popup!=null){  mymap.removeLayer(popup);}
        mymap.removeEventListener("click");
        removeDiv("closeMeasure");
    });

    mymap.addEventListener("click",function (e) {
        switch (num){
            case 0:
                points.push([e.latlng.lat,e.latlng.lng]);

                mlatlng=L.latLng(e.latlng.lat,e.latlng.lng);
                num++;
                break;
            case 1:
                p2=[e.latlng.lat,e.latlng.lng];
                p=p2;
                num++;
                points.push([e.latlng.lat,e.latlng.lng]);
                line=L.polyline(points,{color:'red'});
                cacheLayer.addLayer(line);
                mymap.addLayer(cacheLayer);
//两点测距
                var point2=L.latLng(p2[0],p2[1]);
                var dis=mlatlng.distanceTo(point2);
                aDis=dis;
                dis=dis.toFixed(3);
//弹出值
                mlatlng=L.latLng(e.latlng.lat,e.latlng.lng);
                popup = L.popup()
                    .setLatLng(mlatlng)
                    .setContent('<p>长度(米)<p/>'+dis)
                    .openOn(mymap);
                break;
            case 2:
                //num=0;
                p=[e.latlng.lat,e.latlng.lng];
                points.push(p);
                mymap.removeLayer(cacheLayer);
                cacheLayer.removeLayer(line);

                var dis=countDis(p2,p);
                aDis=aDis+dis;

//弹出值
                mlatlng=L.latLng(e.latlng.lat,e.latlng.lng);
                popup = L.popup()
                    .setLatLng(mlatlng)
                    .setContent('<p>长度(米)<p/>'+aDis.toFixed(3))
                    .openOn(mymap);
                line=L.polyline(points,{color:'red'});
                cacheLayer.addLayer(line);
                mymap.addLayer(cacheLayer);
                p2=p;
                break;
            default:break;
        }
    });
}
function countDis(p1,p2) {
    var p3=L.latLng(p1[0],p1[1]);
    var p4=L.latLng(p2[0],p2[1]);
    return p3.distanceTo(p4);
}
//测面积
function measureArea() {
    removeDiv("message");
    var region=null;
    var latlngs=[];
    var popup=null;

    var cacheLayer=new L.FeatureGroup();

    var closeMbtn=createCloseBtn();
    closeMbtn.onclick=function () {
        mymap.removeEventListener("click");
        if(latlngs.length>1){
            mymap.removeLayer(cacheLayer);

        }
        if(popup!=null){mymap.removeLayer(popup);}
        removeDiv("closeMeasure");
    };
    mymap.addEventListener("click",function (e) {
        if(latlngs.length<2){
            latlngs.push([e.latlng.lat,e.latlng.lng]);
        }else{if(latlngs.length>2){
            mymap.removeLayer(cacheLayer);
            cacheLayer.removeLayer(region);
        }
            latlngs.push([e.latlng.lat,e.latlng.lng]);
            region=L.polygon(latlngs,{color:'red'});
            cacheLayer.addLayer(region);
            mymap.addLayer(cacheLayer);
            var areas=countArea(latlngs);
            areas=areas.toFixed(2);

            popup = L.popup()
                .setLatLng(region.getCenter())
                .setContent('<p>面积(平方米)<p/>'+areas)
                .openOn(mymap);
        }
    })
}
function countArea(latLngs) {
    var pointsCount = latLngs.length,
        area = 0.0,
        d2r = 0.017453292519943295769236907684886,
        p1, p2;
    for (var i = 0; i < pointsCount; i++) {
        console.log("i"+i);
        p1 = latLngs[i];
        p2 = latLngs[(i + 1) % pointsCount];
        area += ((p2[1] - p1[1]) * d2r) *
            (2 + Math.sin(p1[0] * d2r) + Math.sin(p2[0] * d2r));
    }
    area = area * 6378137.0 * 6378137.0 / 2.0;
    return  Math.abs(area);
}

/**
 * 数据采集
 */
function chooseCapture() {
    var div=document.createElement('div');
    div.id="message";
    document.body.appendChild(div);
    div.innerHTML=
        "<div ><table><tr>" +
        "<td class='captureWay' onclick='takePhoto()'><img src='img/iphoto.png'/><br/>图像采集</td>" +
        "<td class='captureWay' onclick='takeVideo()'><img src='img/dossier-video.png'/><br/>视频采集</td>" +
        "</tr></table></div>" +
        "<div id='removeMessage' onclick='removeParent(this)'>取消</div>";

    div.style.opacity=0;
    $("#message").animate({opacity:1});
}

function takePhoto() {
    removeDiv("message");
    var path = window.Android.photo();
    endCapture(path, true);

}

function takeVideo() {
    removeDiv("message");
    var path = window.Android.video();
    endCapture(path, false);
}

function endCapture(path, bool) {
    var div = document.createElement('div');
    div.id = "LayerControlPanel";
    document.body.appendChild(div);
    div.innerHTML =
        "<div id='captureTitle'>数据采集</div>" +
        "<div id='mediaContainer'></div>" +
        "<div class='captureText'>经度:</div>" +
        "<div class='captureText'>纬度:</div>" +
        "<div class='captureText'>路径:</div>" +
        "<div class='captureText' style='width: 50vw;margin-left:15vw;'></div>" +
        "<div id='nameInput'>名称:<input id='mediaName'placeholder='请输入名称'/></div>"+
        "<div class='capBtn' onclick='saveCaptureData()'>储存</div>" +
        "<div class='capBtn' onclick='upData()'>上传</div>"+
        "<div class='capBtn' onclick='reCapture()'>重新拍摄</div>"
    ;
    $("#LayerControlPanel").animate({width: '70vw'});
    touchSlide(div);
    var captureText=document.getElementsByClassName("captureText");
    captureText[0].innerHTML+=window.Android.getLongitude();
    captureText[1].innerHTML+=window.Android.getLatitude();
    captureText[3].innerHTML+=path;
    imgPath=path;
}

function capPicReturn(){
 var imgTarget=document.getElementById("mediaContainer");
    var img=document.createElement('img');
    imgPath="FILE://"+imgPath;
    img.src=imgPath;
    imgTarget.appendChild(img);
}

function capVideoReturn(){
 var imgTarget=document.getElementById("mediaContainer");
 imgTarget.innerHTML="<video id='video' controls='controls'>播放失败</video><br/>"
    imgPath="FILE://"+imgPath;

    document.getElementById("video").src=imgPath;

}

/**
 * 重新采集
 */
function reCapture(){
removeLayerControl();
chooseCapture();
}
function upData() {
    var mediaName=document.getElementById("mediaName").value;
    window.Android.upLoadData(mediaName);
}
/**
 * 保存采集到的数据
 */
function saveCaptureData(){
var mediaName=document.getElementById("mediaName").value;
window.Android.saveCaptureData(mediaName);
}

/**
 * 地图标记功能
 */
function markerManager(bool) {
    if (bool) {
        mymap.addEventListener("click", function (e) {
            mapAddMarker(e.latlng.lat, e.latlng.lng);
        });
    } else {
        mymap.removeEventListener("click");
    }
}
function mapAddMarker(lat,lng) {
    var div=document.createElement('div');
    div.id="message";
    document.body.appendChild(div);
    div.innerHTML=
        "<div class='messageTitle'>添加地图标记</div>"+
        "<div class='captureText' style='color: white;width: 80vw;margin-left: 5vw;'>内容:<input type='text' value='' id='markerContent'  placeholder='输入标注内容'/></div>"+
        "<div class='captureText' style='color: white;width: 80vw;margin-left: 5vw;'>类型:" +
        "<ul>" +
        "<li class='markerType' onclick='chooseMarker(this)'><img src='icon/Mapicon1.png'/>图标1</li>" +
        "<li class='markerType' onclick='chooseMarker(this)'><img src='icon/Mapicon2.png'/>图标2</li>" +
        "<li class='markerType' onclick='chooseMarker(this)'><img src='icon/Mapicon3.png'/>图标3</li>" +
        "<li class='markerType' onclick='chooseMarker(this)'><img src='icon/Mapicon4.png'/>图标4</li>" +
        "</ul>"+
        "</div>"+
        "<div id='removeMessage'>确定</div>";
    div.style.opacity=0;
    $("#message").animate({opacity:1});
    var value=document.getElementById("markerContent");
    $("#removeMessage").click(function () {
        addMarker(lat,lng,value.value);
    });
}
function chooseMarker(obj) {
    var markerAll=document.getElementsByClassName('markerType');
    for(var i=0;i<markerAll.length;i++){
        if(markerAll[i]==obj){
            obj.style.border="2px dotted yellow";
            markertype=i;
        }else{
            markerAll[i].style.border="none";
        }
    }

}
/**
 * 标记地图
 */
function addMarker(lat,lng,con) {
    removeDiv("message");
    var type=markertype+1;
    var marPath="icon/Mapicon"+type+".png";
    var myIcon = L.icon({
        iconUrl: marPath,
        iconSize: [90, 90],
        iconAnchor: [22, 94],
        popupAnchor: [-3, -76],
        shadowSize: [68, 95],
        shadowAnchor: [22, 94]
    });
    var marker=L.marker([lat,lng],{icon:myIcon}).addTo(mymap);
    marker.bindPopup(con).openPopup();
    marker.on("click",function () {
        if(time != 0){
            time=new Date().getTime()-time;
            if (time < 1200) {
                mymap.removeLayer(marker);
                time = 0;
            }else{
                time=new Date().getTime();
            }
        }else{
            time=new Date().getTime();
        }
    })
}

/**
 *控制比例尺
 */
function ruleScale(bool) {
    var logo=document.getElementById("logo");
    if (bool) {
        rule = L.control.scale().addTo(mymap);
        logo.style.display="none";
    } else {
        mymap.removeControl(rule);
        logo.style.display="block";
    }
}